<template>
    <div>
        <el-upload class="src-uploader" :action="baseUrl + '/api/upload'" :show-file-list="false" :on-success="handleAvatarSuccess"
            method="POST" nam="file" :headers="{ Authorization: getToken('token') }"
            :before-upload="beforeAvatarUpload">
            <img v-if="src" :src="srcToPath(src)" class="src" />
            <el-icon v-else class="src-uploader-icon">
                <Plus />
            </el-icon>
        </el-upload>
    </div>
</template>
<script setup>
import srcToPath from '@/utils/srcToPath.js'
import { getToken } from '@/utils/auth.js'
import { baseUrl } from '@/utils/http.js'
const emit = defineEmits(['changeMsg'])
const props = defineProps({
    src: {
        type: String,
        required: true
    }
})

const handleAvatarSuccess = (
    response,
    uploadFile
) => {
    console.log(response);
    // props.src = response.path
    emit('update:src', response.path)  
}

const beforeAvatarUpload = (rawFile) => {
    const fileTypes = ["image/jpeg", "image/jpg", "image/png", "image/gif"];

    const mimeType = fileTypes.includes(rawFile.type.split('/')[1]);
    if (mimeType) {
        ElMessage.error('src picture must be jpeg|jpg|png|gif format!')
        return false
    } 
     if (rawFile.size / 1024 / 1024 > 2) {
        ElMessage.error('src picture size can not exceed 2MB!')
        return false
    }
    return true
}
</script>


<style lang="scss" scoped>
.src-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.src-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.src-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}

.src-uploader .src {
    width: 178px;
    height: 178px;
    display: block;
}
</style>
